import React, { Component } from "react";
import { View, Text, Alert } from "react-native";
import { ListItem, Header, Button, Input } from "react-native-elements";
import DateTimePicker from "react-native-modal-datetime-picker";
import moment from "moment";
import CustomHeader from "../../components/CustomHeader";
import { request } from "../../utils";
import { MyButton } from "../../components/MyButton";

const rType = [
  "大便",
  "小便",
  "纸尿裤",
  "母乳",
  "奶粉",
  "辅食",
  "身高",
  "体重"
];

class AddRecord extends Component {
  constructor(props) {
    super(props);
    this.state = {
      itemId: props.navigation.getParam("itemId", 0),
      pId: props.navigation.getParam("pId", 0),
      selectedType: "奶粉",
      selectedTime: moment().format("YYYY-MM-DD HH:mm"),
      showSelectTime: false,
      remarks: [],
      remark: ""
    };
  }

  componentDidMount() {
    const { itemId } = this.state;
    if (itemId) {
      request("record/info", { id: itemId }, item =>
        this.setState(
          {
            selectedTime: moment(item.RecordTime).format("YYYY-MM-DD HH:mm"),
            selectedType: item.RType,
            remark: item.Remark
          },
          this.getRemarkHistory
        )
      );
    } else {
      this.getRemarkHistory();
    }
  }
  getRemarkHistory = () => {
    const { pId, selectedType } = this.state;
    request("record/remarkHistory", { pId, rType: selectedType }, remarks =>
      this.setState({ remarks })
    );
  };

  提交 = () => {
    const { selectedType, selectedTime, remark, pId, itemId } = this.state;
    const { navigation } = this.props;
    if (selectedType == "奶粉" && !remark) {
      Alert.alert("请在备注里输入奶粉容量");
      return;
    }
    request(
      "record/add",
      {
        RType: selectedType,
        RecordTime: selectedTime,
        Remark: remark,
        PId: pId,
        Id: itemId
      },
      _ => navigation.goBack(),
      data => Alert.alert(data)
    );
  };

  删除 = _ => {
    const { itemId } = this.state;
    const { navigation } = this.props;
    Alert.alert("确定要删除这条记录吗?", "", [
      { text: "取消" },
      {
        text: "确定",
        onPress: _ => {
          request(
            "record/delete",
            { id: itemId },
            _ => navigation.goBack(),
            data => Alert.alert(data)
          );
        }
      }
    ]);
  };

  showRemark = (remarks, remark) => {
    if (!remarks) {
      remarks = [];
    }
    return (
      <View>
        <ListItem
          title="备注"
          titleStyle={{
            width: 100
          }}
          rightElement={
            <Input
              keyboardType="decimal-pad"
              containerStyle={{
                maxWidth: 200
              }}
              inputStyle={{
                textAlign: "right"
              }}
              value={remark}
              onChangeText={remark => this.setState({ remark })}
            />
          }
          bottomDivider
        />

        <ListItem
          title="备注历史"
          titleStyle={{
            width: 100
          }}
          bottomDivider
          rightElement={
            <View
              style={{
                maxWidth: 280,
                display: "flex",
                flexDirection: "row",
                flexWrap: "wrap",
                justifyContent: "flex-end"
              }}
            >
              {remarks.map((item, index) => {
                return (
                  <MyButton
                    title={item}
                    key={index}
                    onPress={_ => {
                      this.setState({ remark: item });
                    }}
                    type="clear"
                  />
                );
              })}
            </View>
          }
        />
      </View>
    );
  };

  render() {
    const {
      selectedType,
      selectedTime,
      showSelectTime,
      itemId,
      remarks,
      remark
    } = this.state;

    const showRemark =
      selectedType == "奶粉" ||
      selectedType == "身高" ||
      selectedType == "体重";
    return (
      <View>
        <CustomHeader
          title={itemId ? "编辑记录" : "添加记录"}
          right="check"
          onRightClick={this.提交}
        />
        <ListItem
          title="时间"
          bottomDivider
          rightElement={
            <MyButton
              title={selectedTime}
              onPress={_ =>
                this.setState({
                  showSelectTime: true
                })
              }
            />
          }
        />

        <ListItem
          title="类型"
          titleStyle={{
            width: 100
          }}
          bottomDivider
          rightElement={
            <View
              style={{
                maxWidth: 300,
                display: "flex",
                flexDirection: "row",
                flexWrap: "wrap",
                justifyContent: "flex-end"
              }}
            >
              {rType.map((item, index) => {
                const isSelected = selectedType == item;
                return (
                  <MyButton
                    buttonStyle={{
                      marginLeft: 6,
                      marginTop: 6,
                      backgroundColor: isSelected ? "tomato" : "white"
                    }}
                    titleStyle={{
                      color: isSelected ? "white" : "tomato"
                    }}
                    title={item}
                    key={index}
                    onPress={_ => {
                      this.setState({ selectedType: item });
                    }}
                  />
                );
              })}
            </View>
          }
        />

        {showRemark && this.showRemark(remarks, remark)}

        {itemId ? (
          <MyButton
            title="删除"
            buttonStyle={{
              margin: 16
            }}
            onPress={this.删除}
          />
        ) : null}

        <DateTimePicker
          isVisible={showSelectTime}
          onConfirm={date => {
            let recordTime = moment(date);
            if (recordTime.isAfter(moment())) {
              recordTime = recordTime.subtract(1, "days");
            }
            this.setState({
              showSelectTime: false,
              selectedTime: recordTime.format("YYYY-MM-DD HH:mm")
            });
          }}
          date={moment(selectedTime).toDate()}
          onCancel={_ => this.setState({ showSelectTime: false })}
          is24Hour={true}
          mode="time"
        />
      </View>
    );
  }
}

export default AddRecord;
